/**
 * Company : SIANGKLOM.
 * Created By : Chatree Siangklom
 * Created On : Sep 26, 2013  1:51:10 PM 
 * e-Mail : dr_chatree@hotmail.com
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : com.tis.encryption
 * File Name : AESencrp.java
 * TODO
 */
package com.tis.encryption;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @author Chatree Siangklom of Administrator
 * Date =Sep 26, 2013 : 1:51:10 PM 
 * CreateBy=Chatree Siangklom
 * TODO
 */
public class AESencrp {
	
	private static final String ALGO = "AES";
	private static final byte[] keyValue = new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };
	
	
	/**
	 * Date =Sep 26, 2013 : 1:53:11 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 * @param Data
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String Data) throws Exception {
	        Key key = generateKey();
	        Cipher c = Cipher.getInstance(ALGO);
	        c.init(Cipher.ENCRYPT_MODE, key);
	        byte[] encVal = c.doFinal(Data.getBytes());
	        String encryptedValue = new BASE64Encoder().encode(encVal);
	        
	        return AESUrlencrp.ReplaceSpacialchar(encryptedValue);
	}

	/**
	 * 
	 * Date =Sep 26, 2013 : 1:53:18 PM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 * @param encryptedData
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String encryptedData) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = new BASE64Decoder().decodeBuffer(AESUrlencrp.RedoReplaceSpacialchar(encryptedData));
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }
    
    /**
     * 
     * Date =Sep 26, 2013 : 1:52:32 PM 
     * CreateBy=Chatree Siangklom
     * TODO
     * @return
     * @throws Exception
     */
    private static Key generateKey() throws Exception {
        Key key = new SecretKeySpec(keyValue, ALGO);
        return key;
    }
    
    
    public static void main(String [] args) {
    	try {
    		
    		String Data = "tis@(8]";
    		String encryptedData = AESencrp.encrypt(Data);
    		String decryptData = AESencrp.decrypt(encryptedData);
    		System.out.println("encryptedData =" + encryptedData);
    		System.out.println("decryptData =" + decryptData);
    		
    		
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    }

    
}
